package org.awenlice.playerdailyshop.event;

import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import org.awenlice.playerdailyshop.data.PlayerBuyShopData;
import org.awenlice.playerdailyshop.data.PlayerBuyShopDataManager;
import org.awenlice.playerdailyshop.data.PlayerShopData;
import org.awenlice.playerdailyshop.data.PlayerShopDataManager;
import org.awenlice.playerdailyshop.gui.BuyShopGui;
import org.awenlice.playerdailyshop.gui.ShopGui;

@Mod.EventBusSubscriber
public class PlayerEventHandler {
    @SubscribeEvent
    public static void onPlayerLogout(PlayerEvent.PlayerLoggedOutEvent event) {
        if (event.getEntity() instanceof ServerPlayer) {
            ServerPlayer player = (ServerPlayer) event.getEntity();

            // 保存出售商店数据
            PlayerShopData sellShopData = PlayerShopDataManager.get(player);
            sellShopData.setDirty(); // 标记数据为脏，需要保存

            // 保存收购商店数据
            PlayerBuyShopData buyShopData = PlayerBuyShopDataManager.get(player);
            buyShopData.setDirty(); // 标记数据为脏，需要保存
        }
    }

    @SubscribeEvent
    public static void onPlayerLogin(PlayerEvent.PlayerLoggedInEvent event) {
        if (event.getEntity() instanceof ServerPlayer) {
            ServerPlayer player = (ServerPlayer) event.getEntity();

            // 生成并加载出售商店数据
            PlayerShopData sellShopData = PlayerShopDataManager.get(player);
            if (sellShopData.getShopItems().isEmpty()) {
                sellShopData.setShopItems(ShopGui.generateShopItems());
            }

            // 生成并加载收购商店数据
            PlayerBuyShopData buyShopData = PlayerBuyShopDataManager.get(player);
            if (buyShopData.getBuyShopItems().isEmpty()) {
                buyShopData.setBuyShopItems(BuyShopGui.generateBuyShopItems());
            }
        }
    }
}
